package com.dhh.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem;
import greendroid.widget.QuickAction;
import greendroid.widget.QuickActionGrid;
import greendroid.widget.QuickActionWidget;
import greendroid.widget.ActionBarItem.Type;
import greendroid.widget.QuickActionWidget.OnQuickActionClickListener;
import com.dhh.R;
import com.dhh.dao.DataBaseHelper;
import com.dhh.util.CUtil;
import com.dhh.util.Constant;
import com.dhh.util.manager.FoodLogManager;
import com.dhh.util.manager.GoalManager;
import com.dhh.util.manager.PlanManager;
import com.dhh.util.manager.WeightManager;
import com.dhh.vo.DailyEnergy;
import com.dhh.vo.FoodPlan;
import com.dhh.vo.Goal;
import com.dhh.vo.Weight;
import com.flotandroidchart.flot.FlotChartContainer;
import com.flotandroidchart.flot.FlotDraw;
import com.flotandroidchart.flot.Options;
import com.flotandroidchart.flot.data.PointData;
import com.flotandroidchart.flot.data.SeriesData;
import com.flotandroidchart.flot.data.TickData;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

public class HomeActivity extends GDActivity implements OnClickListener{
	private Goal goal;
	private Weight weight;
	private FoodPlan plan; 
	private DataBaseHelper db;
	private GoalManager gManager;
	private WeightManager wManager;
	private PlanManager pManager;
	private FoodLogManager flManager;
	
	private TextView gWeight;
	private TextView cWeight;
	private TextView totalGain;
	private TextView dayGain;
	private TextView todayDate;
	private TextView cEnergy;
	private TextView pEnergy;
	
	TextView[] ds;
	private TextView d1;
	private TextView d2;
	private TextView d3;
	private TextView d4;
	private TextView d5;
	private TextView d6;
	private TextView d7;
	
	TextView[] gs;
	private TextView g1;
	private TextView g2;
	private TextView g3;
	private TextView g4;
	private TextView g6;
	private TextView g5;
	private TextView g7;
	
	TextView[] cs;
	private TextView c1;
	private TextView c2;
	private TextView c3;
	private TextView c4;
	private TextView c5;
	private TextView c6;
	private TextView c7;

	private LinearLayout todayLogLayout;
    private QuickActionWidget mGrid;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); 
        setActionBarContentView(R.layout.home);
        initActionBar();      

        db = new DataBaseHelper(getBaseContext());
        db.openDataBase();        
        gManager = new GoalManager(db);
        wManager = new WeightManager(db);
        pManager = new PlanManager(db);
        flManager = new FoodLogManager(db);        
        goal = gManager.getCurrentGoal();
        weight = wManager.getCurrentWeight();
        plan = pManager.getCurrentPlanSimple();       
        
        initView();
        initChart();
        fillData();
        initList(flManager.getEnergyLog()); 
    } 
    
    @Override
    public void onRestart(){
        super.onStart();  
        Intent intent = new Intent(this,HomeActivity.class);
        startActivity(intent);
    }
    
    @Override
	public void onStart() {
        super.onStart();  
    }
    
    @Override
    public void onResume(){
    	super.onResume();
        db.openDataBase();       
    }
    
    @Override
	protected void onPause(){
		super.onPause();
		if (db != null) {
			db.close();
		}
	}
    
    @Override
	protected void onStop(){
		super.onStop();
	}
    
    private void initActionBar(){
        getActionBar().removeViewAt(0);
        getActionBar().setTitle("Weight Gain Assistant");
        getActionBar().setBackgroundColor(Color.rgb(14, 166, 249));
        addActionBarItem(Type.List);
        addActionBarItem(Type.Add).getItemView()
	        .setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(HomeActivity.this,FoodAddActivity.class);
	            	intent.putExtra(Constant.FROM_ACTIVITY, Constant.FA_HOME);
	            	intent.putExtra("planId", plan.getId());
	            	HomeActivity.this.startActivity(intent);
				}}); 
        prepareQuickActionGrid();
    }
    
    private void initView(){
    	gWeight = (TextView) this.findViewById(R.id.h_target_weight);
        cWeight = (TextView) this.findViewById(R.id.h_current_weight);
        totalGain = (TextView) this.findViewById(R.id.h_total_gain);
        dayGain = (TextView) this.findViewById(R.id.h_day_gain);
        cEnergy = (TextView) this.findViewById(R.id.h_current_energy);
        pEnergy = (TextView) this.findViewById(R.id.h_plan_energy);
        todayDate = (TextView) this.findViewById(R.id.h_date);
        
        d1 = (TextView) this.findViewById(R.id.h_d1);
        d2 = (TextView) this.findViewById(R.id.h_d2);
        d3 = (TextView) this.findViewById(R.id.h_d3);
        d4 = (TextView) this.findViewById(R.id.h_d4);
        d5 = (TextView) this.findViewById(R.id.h_d5);
        d6 = (TextView) this.findViewById(R.id.h_d6);
        d7 = (TextView) this.findViewById(R.id.h_d7);
        ds = new TextView[]{d7,d6,d5,d4,d3,d2,d1};
        
        g1 = (TextView) this.findViewById(R.id.h_g1);
        g2 = (TextView) this.findViewById(R.id.h_g2);
        g3 = (TextView) this.findViewById(R.id.h_g3);
        g4 = (TextView) this.findViewById(R.id.h_g4);
        g5 = (TextView) this.findViewById(R.id.h_g5);
        g6 = (TextView) this.findViewById(R.id.h_g6);
        g7 = (TextView) this.findViewById(R.id.h_g7);
        gs = new TextView[]{g7,g6,g5,g4,g3,g2,g1};
        
        c1 = (TextView) this.findViewById(R.id.h_c1);
        c2 = (TextView) this.findViewById(R.id.h_c2);
        c3 = (TextView) this.findViewById(R.id.h_c3);
        c4 = (TextView) this.findViewById(R.id.h_c4);
        c5 = (TextView) this.findViewById(R.id.h_c5);
        c6 = (TextView) this.findViewById(R.id.h_c6);
        c7 = (TextView) this.findViewById(R.id.h_c7);
        cs = new TextView[]{c7,c6,c5,c4,c3,c2,c1};
        
        todayLogLayout = (LinearLayout) this.findViewById(R.id.home_current_foodlog);
        todayLogLayout.setOnClickListener(this);
    }
    
    private void fillData(){
    	gWeight.setText(goal.getTargetWeight());
    	cWeight.setText(weight.getWeight());
    	totalGain.setText(wManager.getTotalGain());
    	dayGain.setText(wManager.getTodayGain());
    	pEnergy.setText(pManager.getCurrentPlan().getEnergy());
    	cEnergy.setText(flManager.getTodayEnergy()); 
    	todayDate.setText(CUtil.getDate("yyyy-MM-dd", "EEE,MMM dd", weight.getDate()));
    }
    
    public void initList(List<DailyEnergy> ws){
    	SimpleDateFormat sfs = new SimpleDateFormat("EEE");
		SimpleDateFormat sfl = new SimpleDateFormat("yyyy-MM-dd");
		
    	for(int i=0; i<ws.size(); i++){
    		try {
    			DailyEnergy de = ws.get(i);
    			ds[i].setText(sfs.format(sfl.parse(ws.get(i).getDate())));
    			cs[i].setText(ws.get(i).getEnergy());
    			if("-".equals(de.getEnergy())){
    				Date pd = sfl.parse(plan.getDate());
    				Date fd = sfl.parse(de.getDate());
    				if(fd.after(pd)){
    					gs[i].setBackgroundResource(R.drawable.ball_red);
    				}else{
    					gs[i].setBackgroundColor(Color.WHITE);
    				}
    			}else{
    				if(de.checkHeath()){
						gs[i].setBackgroundResource(R.drawable.ball_green);
					}else{
						gs[i].setBackgroundResource(R.drawable.ball_red);
					}
    			}
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    }
    
    public void initChart(){
    	List<Weight> lst = wManager.getChartData(7);    	
    	List<Weight> wl = new ArrayList<Weight>();
    	for(int i=lst.size()-1; i>=0; i--){
    		wl.add(lst.get(i));
    	}  
    	Vector<SeriesData> sds = new Vector<SeriesData>();	
    	
		SeriesData sd1 = new SeriesData();		
		Vector<PointData> pds1 = new Vector<PointData>();		
		for(int i=0; i < wl.size(); i++) {
			pds1.add(new PointData(i, Double.parseDouble(wl.get(i).getWeight())));
		}
		sd1.setData(pds1);
		
		SeriesData sd2 = new SeriesData();
		Vector<PointData> pds2 = new Vector<PointData>();
		Double[] weight = new Double[]{64.5,64.5,64.5,64.5,64.5};
		for(int i=0; i < weight.length; i++) {
			pds2.add(new PointData(i, weight[i]));
		}
		sd2.setData(pds2);	
		
		//sd1.label = "Now";
		//sd2.label = "Goal";
		
		if(pds1.size()>0)
			sds.add(sd1);
		//sds.add(sd2);	
		
        Options opt = new Options();		
		opt.grid.hoverable = false;		
		opt.yaxis.ticks = new Integer(6);
		opt.series.lines.setShow(true);
		opt.series.points.show = true;	
		opt.yaxis.tickDecimals = 1;
		
		SimpleDateFormat sfs = new SimpleDateFormat("MM/dd");
		SimpleDateFormat sfl = new SimpleDateFormat("yyyy-MM-dd");
		Vector<TickData> ticks = new Vector<TickData>();
		for(int i=0; i<wl.size(); i++){
			try {
				ticks.add(new TickData(i, sfs.format(sfl.parse(wl.get(i).getDate()))));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		opt.xaxis.ticks = ticks;
		
		FlotDraw fd = new FlotDraw(sds, opt, null);
        FlotChartContainer tv = (FlotChartContainer)this.findViewById(R.id.flotdraw);
        tv.setDrawData(fd);
    }    

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.home_current_foodlog){
			Intent intent = new Intent(HomeActivity.this,FoodLogDetailActivity.class);
			intent.putExtra(Constant.C_LOG_DATE, CUtil.getToday());
			startActivity(intent);
		}		
	}
	
	private void prepareQuickActionGrid() {
		Resources resources = getBaseContext().getResources();         
        mGrid = new QuickActionGrid(this);
        mGrid.addQuickAction(new HomeQuickAction(this, R.drawable.goal, R.string.home_action_goal));
        mGrid.addQuickAction(new HomeQuickAction(this, R.drawable.plan, R.string.home_action_Plan));
        mGrid.addQuickAction(new HomeQuickAction(this, R.drawable.diet, R.string.home_action_Log));
        mGrid.addQuickAction(new HomeQuickAction(this, R.drawable.weight, R.string.home_action_Weight));
        mGrid.addQuickAction(new HomeQuickAction(this, R.drawable.recipe, R.string.home_action_diet));
        mGrid.addQuickAction(new HomeQuickAction(this, R.drawable.lime, R.string.home_action_food));
        mGrid.setOnQuickActionClickListener(mListener);
        Drawable none = resources.getDrawable(R.drawable.w_body);
        mGrid.setBackgroundDrawable(none);
    }
	
	@Override
    public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
        switch (position) {
            case 0:
            	mGrid.show(item.getItemView());
                break;
            default:
                return super.onHandleActionBarItemClick(item, position);
        }

        return true;
    }
	
	private static class HomeQuickAction extends QuickAction {   
        public HomeQuickAction(Context ctx, int drawableId, int titleId) {
            super(ctx, buildDrawable(ctx, drawableId), titleId);
        }
        
        private static Drawable buildDrawable(Context ctx, int drawableId) {
            Drawable d = ctx.getResources().getDrawable(drawableId);
            return d;
        }
        
    }
	
	private OnQuickActionClickListener mListener = new OnQuickActionClickListener() {
        public void onQuickActionClicked(QuickActionWidget widget, int position) {
        	if(position == 0){
    			Intent i = new Intent(HomeActivity.this, GoalActivity.class);	
    			startActivity(i);
    		}else if(position == 1){
    			Intent i = new Intent(HomeActivity.this, FoodPlanActivity.class);	
    			startActivity(i);
    		}else if(position == 2){
    			Intent i = new Intent(HomeActivity.this, ShowFoodLogActivity.class);	
    			startActivity(i);
    		}else if(position == 3){
    			Intent i = new Intent(HomeActivity.this, WeightLogActivity.class);	
    			startActivity(i);
    		}else if(position == 4){
    			Intent i = new Intent(HomeActivity.this, DietLogActivity.class);	
    			startActivity(i);
    		}else if(position == 5){
    			Intent i = new Intent(HomeActivity.this, FoodAddActivity.class);	
    			startActivity(i);
    		}
        }
    };
}